package com.ecommerce.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ecommerce.common.CommonEnum;
import com.ecommerce.common.ResultBody;
import com.ecommerce.entity.Category;
import com.ecommerce.entity.DataCount;
import com.ecommerce.entity.Product;
import com.ecommerce.service.CategoryService;
import com.ecommerce.service.DataCountService;
import com.ecommerce.service.ProductService;
import com.ecommerce.utils.WrapperUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 商品Controller
 *
 * @author wang
 */
@RestController
@Api(value = "ProductController", tags = {"商品接口"})
@RequestMapping("/product")
@Log4j
public class ProductController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    @Autowired
    private WrapperUtils wrapperUtils;

    @Autowired
    private DataCountService dataCountService;


    /**
     * 查询商品列表
     *
     * @param product  商品
     * @param pageNum  页码
     * @param pageSize 条数
     * @return 商品列表
     */
    @ApiOperation(value = "查询商品列表", notes = "查询商品列表")
    @PostMapping(value = "/productList")
    public ResultBody productList(@RequestBody(required = false) Product product, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        IPage<Product> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Product> wrapper = wrapperUtils.productWrapper(product);
        wrapper.orderByDesc(Product::getCreateTime);
        return ResultBody.ok().data(productService.page(page, wrapper));
    }

    /**
     * 创建商品
     *
     * @param product 商品
     * @return 创建商品情况
     */
    @ApiOperation(value = "创建商品", notes = "创建商品")
    @PostMapping(value = "/createProduct")
    public ResultBody createProduct(@RequestBody Product product) {
        product.setCreateTime(new Date());
        product.setStatus("1");
        product.setDeleted("0");
        boolean save = productService.save(product);
        if (save) {
            return ResultBody.ok().message("创建成功");
        } else {
            return ResultBody.error().message("创建失败");
        }
    }

    /**
     * 修改商品
     *
     * @param product 商品
     * @return 修改商品情况
     */
    @ApiOperation(value = "修改商品", notes = "修改商品")
    @PostMapping(value = "/updateProduct")
    public ResultBody updateProduct(@RequestBody Product product) {
        boolean update = productService.updateById(product);
        if (update) {
            return ResultBody.ok().message("修改成功");
        } else {
            return ResultBody.error().message("修改成功");
        }
    }

    /**
     * 上架商品
     *
     * @param productId 商品Id
     * @return 上架商品情况
     */
    @ApiOperation(value = "上架商品", notes = "上架商品")
    @PostMapping(value = "/shelvesProduct")
    public ResultBody shelvesProduct(@RequestParam String productId) {
        LambdaUpdateWrapper<Product> productWrapper = new LambdaUpdateWrapper<>();
        productWrapper.eq(Product::getProductId, productId).set(Product::getStatus, CommonEnum.SHELVES.getCode());
        boolean update = productService.update(productWrapper);
        if (update) {
            return ResultBody.ok().message("上架商品成功");
        } else {
            return ResultBody.error().message("上架商品失败");
        }
    }

    /**
     * 下架商品
     *
     * @param productId 商品Id
     * @return 下架商品情况
     */
    @ApiOperation(value = "下架商品", notes = "下架商品")
    @PostMapping(value = "/soldOutProduct")
    public ResultBody soldOutProduct(@RequestParam String productId) {
        LambdaUpdateWrapper<Product> productWrapper = new LambdaUpdateWrapper<>();
        productWrapper.eq(Product::getProductId, productId).set(Product::getStatus, CommonEnum.UN_SHELVES.getCode());
        boolean update = productService.update(productWrapper);
        if (update) {
            return ResultBody.ok().message("下架商品成功");
        } else {
            return ResultBody.error().message("下架商品失败");
        }
    }

    /**
     * 删除商品
     *
     * @param productId 商品Id
     * @return 删除商品情况
     */
    @ApiOperation(value = "删除商品", notes = "删除商品")
    @PostMapping(value = "/deleteProduct")
    public ResultBody deleteProduct(@RequestParam String productId) {
        boolean delete = productService.removeById(productId);
        if (delete) {
            return ResultBody.ok().message("删除成功");
        } else {
            return ResultBody.error().message("删除失败");
        }
    }

    /**
     * 查询分类列表
     *
     * @param category 分类
     * @param pageNum  页码
     * @param pageSize 条数
     * @return 分类列表
     */
    @ApiOperation(value = "查询分类列表", notes = "查询分类列表")
    @PostMapping(value = "/categoryList")
    public ResultBody categoryList(@RequestBody(required = false) Category category, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        IPage<Category> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Category> wrapper = wrapperUtils.categoryWrapper(category);
        wrapper.orderByDesc(Category::getCategoryId);
        return ResultBody.ok().data(categoryService.page(page, wrapper));
    }

    /**
     * 创建分类
     *
     * @param category 分类
     * @return 创建分类情况
     */
    @ApiOperation(value = "创建分类", notes = "创建分类")
    @PostMapping(value = "/createCategory")
    public ResultBody createCategory(@RequestBody Category category) {
        category.setDeleted("0");
        boolean save = categoryService.save(category);
        if (save) {
            return ResultBody.ok().message("创建成功");
        } else {
            return ResultBody.error().message("创建失败");
        }
    }

    /**
     * 修改分类
     *
     * @param category 分类
     * @return 修改分类情况
     */
    @ApiOperation(value = "修改分类", notes = "修改分类")
    @PostMapping(value = "/updateCateGory")
    public ResultBody updateCateGory(@RequestBody Category category) {
        boolean update = categoryService.updateById(category);
        if (update) {
            return ResultBody.ok().message("修改成功");
        } else {
            return ResultBody.error().message("修改成功");
        }
    }

    /**
     * 上架分类
     *
     * @param categoryId 分类Id
     * @return 上架分类情况
     */
    @ApiOperation(value = "上架分类", notes = "上架分类")
    @PostMapping(value = "/shelvesCategory")
    public ResultBody shelvesCategory(@RequestParam String categoryId) {
        LambdaUpdateWrapper<Category> categoryWrapper = new LambdaUpdateWrapper<>();
        categoryWrapper.eq(Category::getCategoryId, categoryId).set(Category::getShowStatus, CommonEnum.SHELVES.getCode());
        boolean update = categoryService.update(categoryWrapper);
        if (update) {
            return ResultBody.ok().message("上架分类成功");
        } else {
            return ResultBody.error().message("上架分类失败");
        }
    }

    /**
     * 下架分类
     *
     * @param categoryId 分类Id
     * @return 下架分类情况
     */
    @ApiOperation(value = "下架分类", notes = "下架分类")
    @PostMapping(value = "/soldOutCategory")
    public ResultBody soldOutCategory(@RequestParam String categoryId) {
        LambdaUpdateWrapper<Category> categoryWrapper = new LambdaUpdateWrapper<>();
        categoryWrapper.eq(Category::getCategoryId, categoryId).set(Category::getShowStatus, CommonEnum.UN_SHELVES.getCode());
        boolean update = categoryService.update(categoryWrapper);
        if (update) {
            return ResultBody.ok().message("下架分类成功");
        } else {
            return ResultBody.error().message("下架分类失败");
        }
    }


    /**
     * 删除分类
     *
     * @param categoryId 分类Id
     * @return 删除分类情况
     */
    @ApiOperation(value = "删除分类", notes = "删除分类")
    @PostMapping(value = "/deleteCategory")
    public ResultBody deleteCategory(@RequestParam String categoryId) {
        boolean delete = categoryService.removeById(categoryId);
        changeCategory(categoryId);
        if (delete) {
            return ResultBody.ok().message("删除分类成功");
        } else {
            return ResultBody.error().message("删除分类失败");
        }
    }


    /**
     * 商品详情
     *
     * @param product 商品
     * @return 商品详情
     */
    @ApiOperation(value = "商品详情", notes = "商品详情")
    @PostMapping(value = "/productDetail")
    public ResultBody productDetail(@RequestBody Product product) {
        updateDataCount();
        if (product.getProductId() != null) {
            Product one = productService.getById(product.getProductId());
            Category category = categoryService.getById(one.getCategoryId());
            if (category != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.append("product", one);
                jsonObject.append("category", category);
                return ResultBody.ok().data(jsonObject);
            } else {
                return ResultBody.error().message("没有该商品");
            }
        }
        return ResultBody.error().message("没有该商品");

    }

    private void updateDataCount() {
        LambdaUpdateWrapper<DataCount> dataCountWrapper = new LambdaUpdateWrapper<>();
        dataCountWrapper.eq(DataCount::getDataDate, DateUtil.date().toSqlDate());
        DataCount dataCount = dataCountService.getOne(dataCountWrapper);
        if (dataCount != null) {
            dataCount.setGoodVisitor(dataCount.getGoodVisitor() + 1);
            dataCountService.updateById(dataCount);
        } else {
            DataCount newDataCount = new DataCount();
            newDataCount.setGoodVisitor(1);
            newDataCount.setDataDate(DateUtil.date());
            newDataCount.setPageVisitor(1);
            newDataCount.setUniqueVisitor(1);
            dataCountService.save(newDataCount);
        }
    }

    /**
     * 替换默认分类
     *
     * @param categoryId categoryId
     */
    private void changeCategory(String categoryId) {
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getCategoryId, categoryId);
        List<Product> list = productService.list(productWrapper);
        list.forEach(e -> e.setCategoryId(NumberUtil.parseLong(CommonEnum.CATEGORY.getCode())));
        productService.updateBatchById(list);
    }


}
